﻿/*===================================================
* CLR版本  : 4.0.30319.42000 
* 类名称   : ReferenceMessager
* 文 件 名 : ReferenceMessager 
* 类描述   :
* 创建人   : oream
* 创建时间 : 2018/3/12 1:43:17
* 修改人   : 
* 修改时间 :
* 版本： @version 1.0
=====================================================*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;

namespace Model
{
  [Serializable]
  public class ReferenceData
  {
    public string key;
    public UnityEngine.Object reference;

    public ReferenceData()
    {

    }

    public ReferenceData(string key, UnityEngine.Object reference)
    {
      this.key = key;
      this.reference = reference;
    }
    public ReferenceData(UnityEngine.Object reference)
    {
      this.reference = reference;
    }


  }

  public class ReferenceMessager : MonoBehaviour, ISerializationCallbackReceiver
  {
    public List<ReferenceData> referenceList = new List<ReferenceData>();

    public readonly Dictionary<string, UnityEngine.Object> dicObjectDir = new Dictionary<string, UnityEngine.Object>();


    public T Get<T>(string key) where T : class
    {
      try
      {
        Debug.Log(dicObjectDir.Count);
        UnityEngine.Object tmpObj = this.dicObjectDir[key];
        Debug.Log(tmpObj);
        return tmpObj as T;
      }
      catch (Exception e)
      {
        Debug.LogError(e.ToString());
        return null;
      }

    }


    public void OnAfterDeserialize()
    {
      dicObjectDir.Clear();
      foreach (var item in this.referenceList)
      {
        try
        {
          if (!this.dicObjectDir.ContainsKey(item.key))
          {
            this.dicObjectDir.Add(item.key, item.reference);
            Debug.Log($"已添加:{item.key}");
          }
          else
          {
            Debug.LogWarning($"引用字典已包含这个Key,请检查! key : {item.key}  , Reference : {item.reference}");
          }
        }
        catch (Exception e)
        {
          Debug.LogWarning(e);
        }
      }
    }

    public void OnBeforeSerialize()
    {
      
    }
  }
}
